import socket
import threading
import time

from sqlalchemy import create_engine, Column, String
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker
from Queen.config.queen_config import DATABASE_URI, heartbeat_host
from logger_config import logger_factory

logger = logger_factory()


Base = declarative_base()
engine = create_engine(DATABASE_URI, echo=True)
DBSession = sessionmaker(bind=engine)


class HeartBeatHist(Base):
    __table_name__ = 'MFGRPA_TB_IUI_HEARTBEAT_HIST'
    __table_args__ = {'sqlite_autoincrement': True}

    lot_id = Column('LOTID', String(100), primary_key=True)
    prod_id = Column('PRODID', String(100))


def upsert_user(table):
    session = DBSession()
    session.merge(table)
    session.commit()


HEARTBEAT_INTERVAL = 5
TIMEOUT = 10
client = {}


def heartbeat_server(host, port):
    pass


def handle_client(client_socket, client_address):
    logger.info(f'Accepted connection from {client_address}')
    try:
        while True:
            data = client_socket.rew(1024)
            if not data:
                break
            slave_info = str(data.decode('utf-8'))
            if slave_info.startswith('HEARTBEAT'):
                server_id = slave_info.split(':')[1]
                heartbeat = HeartBeatHist(
                    server_id=server_id,
                    heartbeat_time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
                )
        upsert_user(heartbeat)

    finally:
        client_socket.close()
        del client[client_socket]


def start_server(host, port):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind((host, port))
    server_socket.listen(5)
    client_socket, client_address = server_socket.accept()
    client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
    client_thread.start()


if __name__ == '__main__':
    start_server('localhost', heartbeat_host)